//
//  amazonCall.m
//  amazon_test
//
//  Created by Pierre Guilbert on 7/27/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "AmazonCall.h" 
#pragma mark TableView data source methods

@implementation AmazonCall

- (IBAction)fetchDvds:(id)sender {
	[progress stopAnimation:nil];

	[self setItemNode];
}


- (id)init 
{
	NSLog(@"Amazon Panel opening\n");
	self = [super initWithWindowNibName:@"AmazonWindow"];
	if (self != nil)
	{
		//itemNodes = [[NSArray alloc] init];
	}
	return self;
}



- (NSString *)stringForPath: (NSString *)xpath ofNode:(NSXMLNode *)no { 
    NSError *error; 
    NSArray *nodes = [no nodesForXPath:xpath error:&error]; 
    if (!nodes) { 
        NSAlert *alert = [NSAlert alertWithError:error]; 
        [alert runModal]; 
        return nil; 
    } 
    if ([nodes count] == 0) { 
        return nil;
    } else { 
        return [[nodes objectAtIndex:0] stringValue]; 
    } 
} 

-(void)awakeFromNib {
	[tableView setDoubleAction:@selector(openItem:)];
//	[tableView setAction:@selector(selectItem:)];
	[tableView setTarget:self];
}

-(id)tableView:(NSTableView*)tv objectValueForTableColumn:(NSTableColumn*)tableColumn row:(int)row {
	NSXMLNode	*node = [itemNodes objectAtIndex:row];
	NSString	*xPath = [tableColumn identifier];
	
	return [self stringForPath:xPath ofNode:node];
}

-(void)openItem:(id)sender {
	int row = [tableView clickedRow];
	
	// Nothing clicked.
	if (row == -1) {
		return;
	}
	
	NSXMLNode	*node = [itemNodes objectAtIndex:row];
	NSString	*urlString = [self stringForPath:@"DetailPageURL" ofNode:node];
	
	NSURL		*url = [NSURL URLWithString:urlString];
	
	[[NSWorkspace sharedWorkspace] openURL:url];
}

- (void)setItemNode {
	
	// here we build the url request for amazon
	NSString	*input = [titleTextField stringValue];
	search = [input stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
    NSString *urlString = [NSString  stringWithFormat: 
						   @"http://webservices.amazon.com/onca/xml?"
						   @"Service=AWSECommerceService&"
						   @"SubscriptionId=%@&"
						   @"Operation=ItemSearch&"
						   @"Keywords=%@&"
						   @"SearchIndex=DVD",
						   AWS_ID,
						   search];
	
	
	NSURL *url = [NSURL URLWithString:urlString]; 
	
	
	//NSLog(urlString);
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url 
												cachePolicy:NSURLRequestReturnCacheDataElseLoad 
											timeoutInterval:30];
	
		
	
	//-------------------------------------------------------------------------
	// Fetch the XML response 
	NSData *urlData; 
	NSURLResponse *response; 
	NSError *error; 
	
	
	urlData = [NSURLConnection sendSynchronousRequest:urlRequest 
									returningResponse:&response 
												error:&error];
	
	if (!urlData) { 
		NSAlert *alert = [NSAlert alertWithError:error]; 
		[alert runModal]; 
		return; 
	} 
	//-------------------------------------------------------------------------
	
	//-------------------------------------------------------------------------
	// Parse the XML response from Data
	[doc release]; 
	doc = [[NSXMLDocument alloc] initWithData:urlData 
									  options:0 
										error:&error];
	
	
	NSLog(@"doc = %@", doc); 
	if (!doc) { 
		NSAlert *alert = [NSAlert alertWithError:error]; 
		[alert runModal]; 
		return; 
	} 
	//-------------------------------------------------------------------------
	
	//-------------------------------------------------------------------------
	// create the itemNodes
	[itemNodes release]; 
	itemNodes = [[doc nodesForXPath:@"ItemSearchResponse/Items/Item" 
							  error:&error] retain]; 
	if (!itemNodes) { 
		NSAlert *alert = [NSAlert alertWithError:error]; 
		[alert runModal]; 
		return; 
	}

	[tableView reloadData];
	[progress stopAnimation:nil];

}

-(int)numberOfRowsInTableView:(NSTableView*)tv {
	return [itemNodes count];
}


- (void) dealloc 
{
	[search release];
	[super dealloc];
}

@end
